package com.woniu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniu.common.JwtUtil;
import com.woniu.common.ResultCom;
import com.woniu.controller.dto.LoginRequest;
import com.woniu.entity.Admin;
import com.woniu.mapper.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
   private JwtUtil jwtUtil;

    @Autowired
    private AdminMapper adminMapper;
//    LoginRequest 是一个数据传输对象（DTO)
    @PostMapping("/login")
    public ResultCom login(@RequestBody LoginRequest request) {

        // 1. 验证用户身份（这里简化处理，实际应该加密验证）
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>()
                .eq("name", request.getUsername())
                .eq("password",request.getPassword())
        );

        if (admin == null) {
            return ResultCom.error("用户名或密码错误");
        }
        // 2. 生成JWT token
        String token = jwtUtil.generateToken(admin.getId(), admin.getName());

        // 3. 返回token和用户信息
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", admin);

        return ResultCom.success("登录成功", data);
    }
}
